package com.simple.admin.controller.monitor;

import com.simple.common.constant.Constants;
import com.simple.common.exception.ServiceException;
import com.simple.common.exception.TaskException;
import com.simple.common.utils.StringUtils;
import com.simple.framework.constant.HttpStatus;
import com.simple.framework.core.controller.BaseController;
import com.simple.framework.core.domain.R;
import com.simple.framework.core.domain.vo.PagingVo;
import com.simple.quartz.domain.dto.AddSysJobDto;
import com.simple.quartz.domain.dto.ChangeJobStatusDto;
import com.simple.quartz.domain.dto.ListSysJobDto;
import com.simple.quartz.domain.entity.SysJob;
import com.simple.quartz.service.SysJobService;
import com.simple.quartz.utils.CronUtils;
import com.simple.quartz.utils.ScheduleUtils;
import com.simple.system.annotation.SystemLog;
import com.simple.system.enums.BusinessType;
import org.quartz.SchedulerException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @Description 定时任务调度表(SysJob)表控制器层
 * @Author xiaoke
 * @Date 2024/8/19 20:02
 * @Version 1.0
 */
@RestController
@RequestMapping("/monitor/job")
public class SysJobController extends BaseController {

    private final SysJobService sysJobService;

    public SysJobController(SysJobService sysJobService) {
        this.sysJobService = sysJobService;
    }

    /**
     * 查询定时任务调度表(SysJob)列表
     *
     * @param dto 请求参数
     * @return PagingVo<SysJob>
     */
    @GetMapping
    public R<PagingVo<SysJob>> list(ListSysJobDto dto) {
        return success(sysJobService.list(dto));
    }


    /**
     * 新增定时任务调度
     *
     * @param dto 请求参数
     * @return Long
     */
    @SystemLog(title = "新增定时任务",businessType = BusinessType.INSERT)
    @PostMapping
    public R<Long> create(@RequestBody @Validated AddSysJobDto dto) throws SchedulerException, TaskException {
        check(dto);
        return success(HttpStatus.CREATED, sysJobService.insert(dto));
    }

    /**
     * 修改定时任务调度
     *
     * @param dto 请求参数
     * @return Void
     */
    @SystemLog(title = "修改定时任务",businessType = BusinessType.UPDATE)
    @PutMapping("{id}")
    public R<Void> updateById(@PathVariable("id") Long id, @RequestBody @Validated AddSysJobDto dto) throws SchedulerException, TaskException {
        check(dto);
        sysJobService.update(id, dto);
        return success();
    }

    /**
     * 定时任务状态修改
     *
     * @param id     任务Id
     * @param status 状态
     * @return Boolean
     */
    @SystemLog(title = "修改定时任务状态",businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus/{id}")
    public R<Boolean> changeStatus(@PathVariable Long id, @RequestBody ChangeJobStatusDto status) throws SchedulerException {
        return success(sysJobService.changeStatus(id, status));
    }

    /**
     * 定时任务立即执行一次
     *
     * @param id 主键
     * @return Void
     */
    @SystemLog(title = "执行定时任务",businessType = BusinessType.OTHER)
    @PostMapping("/run/{id}")
    public R<Void> run(@PathVariable Long id) throws SchedulerException {
        boolean result = sysJobService.run(id);
        return result ? success() : fail(HttpStatus.BAD_REQUEST, "任务不存在或已过期！");
    }

    /**
     * 批量删除定时任务调度
     *
     * @param ids 主键集合
     * @return Void
     */
    @SystemLog(title = "删除定时任务",businessType = BusinessType.DELETE)
    @DeleteMapping("/batchDelete/{ids}")
    public R<Void> remove(@PathVariable Set<Long> ids) throws SchedulerException, TaskException {
        sysJobService.deleteJobByIds(ids);
        return success();
    }

    /**
     * 验证请求参数
     *
     * @param dto 请求参数
     */
    private void check(AddSysJobDto dto) {

        String cronExpression = dto.getCronExpression();
        String invokeTarget = dto.getInvokeTarget();

        if (!CronUtils.isValid(cronExpression)) {
            throw new ServiceException("Cron表达式不正确");
        }

        if (StringUtils.containsIgnoreCase(invokeTarget, Constants.LOOKUP_RMI)) {
            throw new ServiceException("目标字符串不允许'rmi'调用");
        }

        if (StringUtils.containsAnyIgnoreCase(invokeTarget, new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            throw new ServiceException("目标字符串不允许'ldap(s)'调用");
        }

        if (StringUtils.containsAnyIgnoreCase(invokeTarget, new String[]{Constants.HTTP, Constants.HTTPS})) {
            throw new ServiceException("目标字符串不允许'http(s)'调用");
        }

        if (StringUtils.containsAnyIgnoreCase(invokeTarget, Constants.JOB_ERROR_STR)) {
            throw new ServiceException("目标字符串存在违规");
        }

        if (!ScheduleUtils.whiteList(invokeTarget)) {
            throw new ServiceException("目标字符串不在白名单内");
        }
    }

}
